package com.lingz.manager.modules.wuxue.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingz.manager.modules.wuxue.entity.HuangshiData;
import com.lingz.manager.modules.wuxue.entity.WaterDeviceInfo;
import com.lingz.manager.modules.wuxue.mapper.WaterDeviceInfoMapper;
import com.lingz.manager.modules.wuxue.service.WaterDeviceInfoService;
import com.lingz.manager.modules.wuxue.utils.DeviceDataUtil;
import com.lingz.manager.modules.wuxue.utils.SendRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * (WaterDeviceInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-12-08 10:23:05
 */
@Service("waterDeviceInfoService")
public class WaterDeviceInfoServiceImpl extends ServiceImpl<WaterDeviceInfoMapper, WaterDeviceInfo> implements WaterDeviceInfoService {

    @Autowired
    WaterDeviceInfoMapper waterDeviceInfoMapper;

    @Value("${shujujiekou.waterConservancy}")
    String waterConservancyUrl;

    @Override
    public void requestWaterDeviceInfoDataToDB() {
        SendRequest request = new SendRequest();
        String jsonResponse = request.sendGet(waterConservancyUrl);
        JSONArray data = JSONArray.parseArray(jsonResponse);
        List<WaterDeviceInfo> waterDeviceInfoList = new ArrayList<>();
        if(data!= null && !data.isEmpty()){
            for(int i = 0 ; i <data.size(); i++){
                JSONObject jsonObject = data.getJSONObject(i);
                try {
                    WaterDeviceInfo waterDeviceInfo = DeviceDataUtil.parseJsonToWaterDeviceData(jsonObject);
                    waterDeviceInfoList.add(waterDeviceInfo);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        waterDeviceInfoMapper.insertBatchSomeColumn(waterDeviceInfoList);
    }

    @Override
    public List<WaterDeviceInfo> findWaterDeviceList() {
        LambdaQueryWrapper<WaterDeviceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(WaterDeviceInfo::getId);
        return waterDeviceInfoMapper.selectList(wrapper);
    }
}

